package tests

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/henrylee2cn/goutil"
	"github.com/steambap/captcha"
	"log"
	"my_gin/utils"
	"strings"
	T "time"
)

// Captcha 输出图片验证码，并设置 Cookie
func Captcha(c *gin.Context) {
	data, _ := captcha.New(150, 50)
	text := strings.ToLower(data.Text)
	time := T.Now().Unix()
	key, ok := utils.GetEnvByKey("APP_KEY")
	if !ok {
		log.Fatal("请在 .env 配置 APP_KEY")
	}
	sign := fmt.Sprintf("%v%v%v", text, key, time)
	signMd5 := goutil.Md5(goutil.StringToBytes(sign))
	value := fmt.Sprintf("time=%v&sign=%v", time, signMd5)
	c.SetCookie("captcha", value, 300, "/", "", false, true)
	data.WriteImage(c.Writer)
}
